package com.rockcent.third.helper;

import com.rockcent.mall.lib.domain.IntegrationChannel;
import com.rockcent.mall.lib.domain.UserInfo;
import com.rockcent.mall.lib.dto.ThirdPartyUserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhangjh on 2017/1/12.
 * user 实体类的帮助工具
 */
@Component
public class UserHelper extends BaseUserHelper {

    private static Logger log = LoggerFactory.getLogger(UserHelper.class);
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取第三方用户登录的token
     *
     * @param userInfo
     * @return
     */
    public String getThirdUserToken(ThirdPartyUserInfoDto userInfo) {
        return DigestUtils.md5Hex(userInfo.getAppKey() + userInfo.getAppSecret() + java.sql.Date.from(Instant.now()).getTime());
    }

    /**
     * @param thirdPartyUserInfoDto
     * @param request
     * @param integrationChannel
     * @return
     */
    public ThirdPartyUserInfoDto setSession(ThirdPartyUserInfoDto thirdPartyUserInfoDto, HttpServletRequest request, IntegrationChannel integrationChannel) {
        String accessToken = getThirdUserToken(thirdPartyUserInfoDto);
        redisTemplate.boundValueOps(UserInfo.REDIS_USER_TOKEN_PREFIX + accessToken).set(integrationChannel.getId().toString());
        Long accessTokenTimer = 2 * 60 * 60L; // 2个小时 生命周期
        redisTemplate.expire(UserInfo.REDIS_USER_TOKEN_PREFIX + accessToken, accessTokenTimer, TimeUnit.SECONDS);
        ThirdPartyUserInfoDto userInfoDto = new ThirdPartyUserInfoDto();
        userInfoDto.setExpiresIn(accessTokenTimer);
        userInfoDto.setAccessToken(accessToken);
        return userInfoDto;
    }

}
